<?php
namespace App\Controllers;

use App\Requests\AppSendSmsRequest;
use App\Requests\PhoneRequest;
use App\Services\SmsService as Service;
use Framework\BaseController;
use Framework\Hope;
use Mews\Captcha\Facades\Captcha;

class SmsController extends BaseController
{
    /**
     * @var Service
     */
    private $service;

    public function __construct(Service $service)
    {
        $this->service = $service;
    }

    /** 提交图形验证码
     * @param AppSendSmsRequest $request
     */
    public function send_sms(AppSendSmsRequest $request)
    {
        $phone = $request->phone();
        $key = $request->key();
        $code = $request->code();
        $flg = captcha_api_check($code, $key);
        if (!$flg && (!Hope::isProduct() && $code != 'ASDF')) {
            $this->retError('图形验证码错误');
        }
        if(!Hope::isProduct()){
            $code = substr($phone, -4);
            $redis = Hope::getRedis();
            $redis->setex("sms:" . $phone, 60 * 5, $code);

        }else{
            //获取短信验证码
            $this->service->sendSmsVerifyCode($phone);
        }

        $this->retSuccess(true);
    }

    /**
     * 获取图形验证码
     */
    public function get_sms()
    {
        $res = Captcha::create('default', true);
        $this->retSuccess($res);
    }

    /**
     * 获取短信验证码
     */
    public function getVerifyCode(PhoneRequest $request)
    {
        $phone = $request->phone();
        $this->service->sendSmsVerifyCode($phone);
        $this->retSuccess(true);
    }
}
